package cn.wangzg.course0602;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

import cn.wangzg.course0602.util.HttpUtil;

public class LoginActivity extends AppCompatActivity {
    private EditText etName;
    private EditText etPwd;
    private CheckBox cbRem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
    }

    private void initView() {
        etName = findViewById(R.id.etName);
        etPwd = findViewById(R.id.etPwd);
        cbRem = findViewById(R.id.cbRem);

        SharedPreferences sp=getSharedPreferences("wan",MODE_PRIVATE);
        String name = sp.getString("name","");
        String pwd=sp.getString("pwd","");
        boolean isRem = sp.getBoolean("isRem", false);
        etName.setText(name);
        etPwd.setText(pwd);
        cbRem.setChecked(isRem);

        CheckBox cbShowPwd = findViewById(R.id.cbShowPwd);
        cbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
    }

    //登录
    public void btnLogin(View view) {
        final String name = etName.getText().toString();
        final String pwd = etPwd.getText().toString();

        //2.发送post请求
        new Thread() {
            @Override
            public void run() {
                //2.发送post请求
                try {
                    String strUrl = "https://www.wanandroid.com/user/login";
                    String data = "username=" + URLEncoder.encode(name, "utf-8")
                            + "&password=" + URLEncoder.encode(pwd, "utf-8");
                    String s = HttpUtil.doPost(strUrl, data);

                    //获取errorCode，如为0，登录成功，跳转
                    JSONObject object = new JSONObject(s);
                    int errcode = object.optInt("errorCode");
                    String errMsg = object.optString("errorMsg");
                    if (errcode == 0) {
                        startActivity(new Intent(LoginActivity.this, WanListActivity.class));
                        //登录成功，是否保存用户名和密码
                        if(cbRem.isChecked()){
                            SharedPreferences sp=getSharedPreferences("wan",MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp.edit();
                            edit.putString("name",name);
                            edit.putString("pwd",pwd);
                            edit.putBoolean("isRem",true);
                            edit.commit();
                        }
                        finish();
                    } else {
                        Toast.makeText(LoginActivity.this, errMsg, Toast.LENGTH_SHORT).show();
                    }

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //注册
    public void btnRegister(View view) {
        final String name = etName.getText().toString();
        final String pwd = etPwd.getText().toString();
        new Thread() {
            @Override
            public void run() {
                //2.发送post请求
                try {
                    String strUrl = "https://www.wanandroid.com/user/register";
                    String data = "username=" + URLEncoder.encode(name, "utf-8")
                            + "&password=" + URLEncoder.encode(pwd, "utf-8")
                            + "&repassword=" + URLEncoder.encode(pwd, "utf-8");
                    String s = HttpUtil.doPost(strUrl, data);

                    //获取errorCode，如为0，提示注册成功
                    JSONObject object = new JSONObject(s);
                    int errcode = object.optInt("errorCode");
                    String errMsg = object.optString("errorMsg");
                    if (errcode == 0) {
                        Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(LoginActivity.this, errMsg, Toast.LENGTH_SHORT).show();
                    }

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    /**
     * 将流转为字符串
     *
     * @param inStream 输入流
     * @return 返回字符串
     * @throws IOException
     */
    private String is2String(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return new String(outStream.toByteArray(), "UTF-8");
    }
}
